package com.leetCode.ListNodeDemo;

import java.util.List;

public class RemoveElementsDemo {
    public static void main(String[] args) {
//        ListNode listNode = new ListNode(1,new ListNode(2,new ListNode(6,new ListNode(3,new ListNode(6)))));
        ListNode listNode = new ListNode(7,new ListNode(7,new ListNode(7,new ListNode(7))));
        ListNode result = removeElements1(listNode,7);
        System.out.println(result);
    }

    /**
     * 给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点 。
     *
     *
     * 示例 1：
     *
     *
     * 输入：head = [1,2,6,3,4,5,6], val = 6
     * 输出：[1,2,3,4,5]
     * 示例 2：
     *
     * 输入：head = [], val = 1
     * 输出：[]
     * 示例 3：
     *
     * 输入：head = [7,7,7,7], val = 7
     * 输出：[]
     */
    public static ListNode removeElements(ListNode head, int val) {
        if (head == null){
            return head;
        }
        ListNode newHead = new ListNode(0);
        ListNode temp = newHead;
        while (head != null){
            if (head.val != val){
                temp.next = new ListNode(head.val);
                temp = temp.next;
            }
            head = head.next;
        }
        return newHead.next;
    }

    public static ListNode removeElements1(ListNode head, int val) {
        ListNode temp = head;
        while (temp != null){
            ListNode next = temp.next;
            if (next != null){
                int nextVal = next.val;
                if (val == nextVal){
                    temp.next = next.next;
                }
            }
            temp = temp.next;
        }
        if (head == null){
            return head;
        }
        return head.val == val ? head.next : head;
    }
}
